package log

import (
	"sync"

	"github.com/alecthomas/log4go"
	"pac/client"
	"pac/packet"
)

type packetLogStruct struct {
	cli    client.Client
	isSend bool
	pkt    packet.Packet
}

var packetLogCh chan *packetLogStruct
var packetLogOnce sync.Once
var packetLogRecordCh chan *packetLogStruct

// PacketLog 打印包信息，并记录
func PacketLog(cli client.Client, isSend bool, pkt packet.Packet) {
	if pkt == nil {
		return
	}

	packetLogOnce.Do(packetLogWorkerInit)

	if !isSend {
		logPacket(cli, isSend, pkt)
	}
	packetLogCh <- &packetLogStruct{cli: cli, isSend: isSend, pkt: pkt}
}

func packetLogWorkerInit() {
	packetLogCh = make(chan *packetLogStruct, 1024000)
	packetLogRecordCh = make(chan *packetLogStruct, 1024000)
	go packetLogWorker()
	go packetLogRecordWorker()
}

func packetLogWorker() {
	for {
		select {
		case p := <-packetLogCh:
			if p.isSend {
				logPacket(p.cli, p.isSend, p.pkt)
			}
			packetLogRecordCh <- p
		}
	}
}

func packetLogRecordWorker() {
	for {
		select {
		case p := <-packetLogRecordCh:
			recordPacket(p.isSend, p.pkt)
		}
	}
}

func logPacket(cli client.Client, isSend bool, pkt packet.Packet) {
	if pkt == nil {
		return
	}

	desc := ""

	if isSend {
		desc += "send"
	} else {
		desc += "recv"
	}

	desc += ": " + pkt.String()

	log4go.Info("%v %v", cli, desc)
}

func recordPacket(isSend bool, pkt packet.Packet) {
	// TODO:
}
